/*!
 * New Resource Strategy.
 * Date: 2015/12/31.
 * Copyright© 2014-2015 Vamaker All Rights Reserved.
 */
require([
  'jquery',
	'pageInit',
  'formAjax',
  'notification',
  'dateRange',
  'moment',
  'select2'
], function ($, vamakerPage, formAjax, VamOpMsg, DateRange, moment, select2) {
  $(function () {
    var $dataFrm = $('#data-frm'),
        $adspaceCheck = $dataFrm.find('input[name="adspace_check"]'),
        $adspaceForm = $('#target_adspace_form');
    $adspaceCheck.on('change', function (evt) {
      var $me = $(this),
          meVal = $me.val();
      if (meVal === 'all') {
        $adspaceForm.addClass('hidden')
      } else {
        $adspaceForm.removeClass('hidden')
      };
      $('#rtb_target_adspace_err').html('');
    });
    $dataFrm.find('input[name="adspace_check"]:checked').trigger('change');
  });
  // Adspace Target
  $(function () {
    var rtbAdspaceListUrl = VAM.getVar('RTB_ADSPACE_LIST'),
        langVer = VAM.getVar("LANGUAGE");
    if (langVer === "zh-CN") {
      langVer = 'zh';
    } else {
      langVer = 'en';
    };
    $('#rtb_target_adspace').select2({
      language: langVer,
      ajax: {
        data: function (params) {
          var $trafficCkb = $('input[name="ad_network[]"]:checked'),
            trafficArr = [];
          for (var i = 0; i < $trafficCkb.length; i++) {
            trafficArr.push($trafficCkb.eq(i).val());
          };
          var query = {
            search: params.term,
            adnetwork: trafficArr.join(','),
            type:'pc'
          };

          return query;
        },
        url: rtbAdspaceListUrl,
        dataType: 'json',
        delay: 1000,
        processResults: function (data) {
          return {
            results: data.items
          }
        },
        cache: true
      },
      minimumInputLength: 1,
    });
    $('#pmp_target_adspace').select2();
  });
  $(function () {
    var $dataFrm = $('#data-frm'),
        $submitBtn = $dataFrm.find('button[type="submit"]'),
        dataFieldRule, options, dataValidator,
        strategyName = $('#strategy_name').val(),
        $operateBtn = $submitBtn.filter('.save-btn'),
        $operateType = $dataFrm.find('.operate-type'),
        $resourceType = $('input[name="resource_type"]'),
        $rtbResourceSetting = $('#rtb_resource_type'),
        $pmpResourceSetting = $('#pmp_resource_type'),
        $market = $('input[name="ad_network[]"]'),
        $adspaceBlack = $('input[name="adspace.black_white_radio"]'),
        $pmpId = $('#pmp_id');
      // console.log($dataFrm);
    $submitBtn.on('click', function (evt) {
      var $me = $(this),
        operate = $me.data('operate'),
        operateTxt;
      operateTxt = '.' + operate + '-btn';
      $operateBtn = $submitBtn.filter(operateTxt);
      $operateType.val(operate);
    });
    $adspaceBlack.on('change', function(){
      var $me = $(this),
          $targetForm = $('.target-form');
      if ($me.val() === 'no_limit') {
        $targetForm.addClass('hidden');
      } else {
        $targetForm.removeClass('hidden');
        $dataFrm.find('input[name="adspace_check"]:checked').trigger('change');
      };
    });
    $('#rtb_target_adspace').on('change', function(){
      var adspaceChecked = $('#rtb_target_adspace :selected').length;
      if (adspaceChecked !== 0 && $('#rtb_target_adspace_err').html() !== '') {
        $('#rtb_target_adspace_err').html('');
      }
    });
    $market.on('change', function(){
      var $me = $(this),
      marketLen = $('input[name="ad_network[]"]:checked').length,
      meVal = $('input[name="ad_network[]"]:checked').val(),
      adspaceBlack = $('input[name="adspace.black_white_radio"]:checked').val(),
      $adspaceChecked = $('#rtb_target_adspace :selected'),
      $errorBox = $('#market_err'),
      flag = true,
      checkState = $me.is(':checked'),
      msg = '';

      $adspaceChecked.each(function(){
        var $adOpt = $(this),
            adVal = $adOpt.val(),
            adText = $adOpt.text(),
            $adTag = $('#target_adspace_form').find('li:contains(' + adText + ')'),
            marketType = adVal.substring(0,1);
        if (marketType === $me.val() && !checkState) {
          $adOpt.prop('selected',false);
          $adTag.remove();
        }
      });
      if (marketLen === 0 && adspaceBlack !== 'no_limit') {
        flag = false;
        msg = VAM.j('Please select at least one!');
      };
      if (!flag) {
        msg = '<em class="checky-default-failure">' + msg + '</em>';
        $errorBox.html(msg);
      } else {
        $errorBox.html('');
      };
    });
    $adspaceBlack.on('change',function(){
      $market.trigger('change');
    });
    $market.trigger('change');
    // $resourceType.on('change', function(){
    //   var $me = $(this),
    //       meVal = $me.val();
    //   if (meVal === '1') {
    //     $rtbResourceSetting.removeClass('hidden');
    //     $pmpResourceSetting.addClass('hidden');
    //   } else {
    //     $pmpResourceSetting.removeClass('hidden');
    //     $rtbResourceSetting.addClass('hidden');
    //   }
    // });
    // $resourceType.filter(':checked').trigger('change');

    // $('#pmp_id').on('change', function (evt) {
    //   var $me = $(this),
    //     $pmpTargetAdspace = $('#pmp_target_adspace'),
    //     newValue = $me.val(),
    //     opData;
    //     opData = {
    //       newValue: newValue,
    //       rnd: (new Date()).getTime()
    //     };
    //     $pmpTargetAdspace.empty();
    //   $.ajax({
    //     url: VAM.getVar('PMP_ADSPACE_LIST'),
    //     data: opData,
    //     type: 'post',
    //     success: function (data) {
    //       if (data.status === 'success') {
    //         VamOpMsg.messager(data);
    //         var pmpAdspaceList = data.data;
    //         for (var i = 0; i < pmpAdspaceList.length; i++) {
    //           $pmpTargetAdspace.append('<option value="" selected>' + pmpAdspaceList[i]['title'] + '</option>');
    //           $('#pmp_target_adspace').select2();
    //         }
    //       } else {
    //         VamOpMsg.messager(data);
    //       }
    //     },
    //     always: function () {
    //       // $me.prop('readonly', false);
    //     }
    //   });
    // });

    $dataFrm.submit(function() {
      var $me = $(this),
          resourceType = $resourceType.filter(':checked').val(),
          adspaceChecked = $('#rtb_target_adspace :selected').length,
          adspaceCheck = $dataFrm.find('input[name="adspace_check"]:checked').val(),
          targetType = $('input[name="adspace.black_white_radio"]:checked').val();
      // PMP ID Validate
      // if (resourceType === '2') {
      //   $pmpId.trigger('blur');
      //   if ($('#pmp_id_err').html() !== '') {
      //     event.preventDefault();
      //     return false;
      //   }
      // };
      if ($('#market_err').html() !== '') {
        event.preventDefault();
        return false;
      };

      if(targetType !== 'no_limit'){
        if (adspaceChecked === 0 && adspaceCheck === 'part') {
          event.preventDefault();
          var msg = VAM.j('Please select at least one!');
          if ($('#rtb_target_adspace_err').html() === '') 
          $('#rtb_target_adspace_err').html('<em class="checky-default-failure">' + msg + '</em>');
          return false;
        };
      };
      $me.ajaxSubmit({
        beforeSubmit: function() {
          $operateBtn.button('loading');
        },
        success: function (data) {
          var next = $operateBtn.data('operate');
          $operateBtn.button('reset');
          if (data.status === 'success') {
            VamOpMsg.messager(data);
            if (next === 'save-next') {
              window.location.href = VAM.getVar('NEXT_URL') + '?solution_id=' + data.data.id + '&strategy_name=' + strategyName;
            } else {
              window.location.href = 'solution-list';
            };
          } else {
            VamOpMsg.messager(data);
          }
        }
      });
      return false;
    });
  });
});
